<script setup>
import MarkdownViewer from "@/components/markdown-viewer/index.vue"
import { copyString, getDocumentStr } from '@/utils/index.js'
import Awesome from '@/icons/Awesome.vue'
import Rubbish from '@/icons/Rubbish.vue'
import DocumentViewer from '@/components/document-viewer/index.vue'
import useUserStore from '@/stores/user.js'
import TextAvatar from '@/components/text-avatar/index.vue'
const imagePrefix = import.meta.env.VITE_IMAGE_SUFFIX
const userStore = useUserStore()


// import {Comment} from '@element-plus/icons-vue'
</script>
<template>
<div>
  <div class="sect" :id="showTools ? 'chat-section' : ''" :class="customClass">
    <div class="chat-section" :id="!showTools ? 'chat-section' : ''">
      <div class="chat-message-box clear-float-after" id="chat-message-box">
        <div class="flex align-items-center padding-30" v-if="appInfo.id">
          <el-row
              style="width: 640px; background: var(--el-bg-color); box-shadow: var(--el-box-shadow-light);"
              :gutter="20"
              class="padding-top-10 border-radius"
          >
            <el-col :span="4">
              <el-image :src="imagePrefix + appInfo.avatar" fit="cover">
                <template #error>
                  <text-avatar :width="86" :text="appInfo.title"/>
                </template>
              </el-image>
            </el-col>
            <el-col :span="20">
              <el-text size="large" style="color: var(--el-text-color-primary)">{{ appInfo.title }}</el-text>
              <br/>
              <el-text type="info" size="small" line-clamp="3">{{ appInfo.introduction }}</el-text>
            </el-col>
          </el-row>
        </div>
        <div v-for="(item, k) in histories" :key="k" :class="item.role">
          <div class="avatar-box">
            <div class="avatar">
              <template v-if="item.role === 'user'">
                <el-icon v-if="!userStore.info.avatar">
                  <component is="User"/>
                </el-icon>
                <el-image v-else :src="imagePrefix + userStore.info.avatar"></el-image>
              </template>
              <template v-else>
                <el-icon v-if="!appInfo.avatar">
                  <component is="Cpu"/>
                </el-icon>
                <el-tooltip v-else effect="dark" :content="appInfo.title" placement="top">
                  <el-image :src="imagePrefix + appInfo.avatar"></el-image>
                </el-tooltip>
              </template>
            </div>
          </div>
          <div class="clear-float-after message-box" :class="item.role === 'user' ? 'float-right' : 'float-left'">
            <div class="time">{{ item.time }}</div>
            <br/>
            <div class="message" v-if="item.role !== 'user'" :id="`history-${k}`">
              <markdown-viewer :value="item.content" :id="`markdown-viewer-${k}`"/>
              <div class="data-file" v-if="item.file_names && item.file_names.length">
                <el-collapse class="bg">
                  <el-collapse-item>
                    <template #title>
                      {{ `找到了${item.file_names.length}个信息来源：` }}
                    </template>
                    <div v-for="(f, i) in item.file_names">
                      来源{{ i + 1 }}：
                      <el-link :href="'#'" @click="downloadFile({name: f, kid: item.knowledge_id})" type="primary"
                               :underline="false" size="mini">{{ f }}
                      </el-link>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
              <el-tooltip effect="dark" content="复制" placement="top" v-if="item.id">
                <el-icon @click="copyString(item.content)">
                  <component is="CopyDocument"/>
                </el-icon>
              </el-tooltip>
              <el-icon style="left: 30px;"
                       v-if="item.id"
                       :class="item.like_type === 1 ? 'primary' : (item.like_type === 2 ? 'info' : '')"
                       @click="likeHandle(item, 1)">
                <Awesome/>
              </el-icon>
              <el-popover
                  v-if="item.id"
                  placement="right"
                  :visible="showDialog && selectItem.id === item.id"
                  :disabled="item.like_type === 1"
                  trigger="click"
                  :width="400"
                  title="请留下您宝贵的意见"
                  :persistent="false"
              >
                <template #reference>
                  <el-icon style="left: 60px;"
                           :class="item.like_type === 2 ? 'primary' : (item.like_type === 1 ? 'info' : '')"
                           @click="likeHandle(item, 2, k)">
                    <Rubbish/>
                  </el-icon>
                </template>
                <el-checkbox-group v-model="question_id">
                  <template v-for="im in cai_questions">
                    <div class="line-height-2xl pw-100">
                      <el-text type="primary">{{ im.k }}</el-text>
                    </div>
                    <div class="pw-100 padding-left-20">
                      <el-checkbox v-for="it in im.v" :key="it.id" :value="it.id" :label="it.id" class="sug-radio-button">
                        {{it.value}}
                      </el-checkbox>
                    </div>
                  </template>
                </el-checkbox-group>
                <br/>
                <br/>
                <div class="line-height-2xl pw-100">
                  <el-text type="primary">进一步反馈</el-text>
                </div>
                <el-input type="textarea" v-model="prompt" show-word-limit maxlength="240" :rows="4"
                          placeholder="输入您补充意见" resize="none"
                          clearable/>
                <div class="margin-top-20 flex justify-content-center">
                  <el-button type="primary" @click="submitSug">提交</el-button>
                  <el-button type="warning" @click="() => {showDialog = false}">关闭</el-button>
                </div>
              </el-popover>
              <el-tooltip effect="dark" content="一键加入笔记" placement="top" v-if="item.id">
                <el-icon @click="addDocument(item.content)" style="left: 90px">
                  <component is="DocumentAdd"/>
                </el-icon>
              </el-tooltip>
            </div>
            <div class="message" v-else :id="`history-${k}`">
<!--              <pre style="background: transparent">{{ item.content }}</pre>-->
              <markdown-viewer :value="item.content" :id="`history-mk-${k}`"/>
              <el-tooltip effect="dark" content="复制" placement="top">
                <el-icon @click="copyString(item.content)">
                  <component is="CopyDocument"/>
                </el-icon>
              </el-tooltip>
            </div>
          </div>
        </div>
        <div class="assistant" v-if="disable && isOutAct">
          <div class="avatar-box">
            <div class="avatar">
              <el-icon v-if="!appInfo.avatar">
                <component is="Cpu"/>
              </el-icon>
              <el-image v-else :src="imagePrefix + appInfo.avatar"></el-image>
            </div>
          </div>
          <div class="clear-float-after float-left message-box">
            <div class="time">{{ now }}</div>
            <br/>
            <div class="message">
              <markdown-viewer :value="aiOutput"/>
            </div>
          </div>
        </div>
        <div v-if="showTools && (!disable || !isOutAct)" class="assistant">
          <div class="avatar-box" style="width: 32px"></div>
          <div class="message" style="background: transparent; padding-left: 0">
              <span v-if="questionLoading">
                <el-icon class="is-loading">
                  <component is="Loading"/>
                </el-icon>
              </span>
            <div v-if="!questionLoading && !showAppInput && histories.length !== 0">
              <el-text>
                你可以{{ histories.length ? '继续' : '' }}问我：
                <el-tooltip effect="dark" content="刷新" placement="top">
                  <el-icon style="position: relative; bottom: 0; margin-left: 20px;" class="primary"
                           @click="refreshQuestions">
                    <component is="Refresh"/>
                  </el-icon>
                </el-tooltip>
              </el-text>
            </div>
            <div v-if="!questionLoading && !showAppInput && histories.length !== 0" v-for="item in questions">
              <el-text type="primary" class="pointer" @click="inputAndEnter(item)">{{ item }}
              </el-text>
            </div>
          </div>
        </div>
        <div class="recommend-apps" v-if="showTools && histories.length === 0 && !showAppInput && showApp && !appInfo.id">
          <div class="h-30 pw-100 flex justify-content-right align-items-center">
            <el-text class="pointer" type="primary" @click="moreApp">
              查看更多
              <el-icon>
                <component is="DArrowRight"/>
              </el-icon>
            </el-text>
          </div>
          <el-row :gutter="14">
            <el-col :span="12" v-for="item in recommendApps">
              <div class="question-item" @click="handleSelectApp(item)">
                <el-row :gutter="10">
                  <el-col :span="5">
                    <el-image :src="imagePrefix + item.avatar"
                              style="width: 60px; height: 60px; border-radius: 4px; margin: 8px 0 0 8px"
                    >
                      <template #error>
                        <text-avatar :text="item.title" :width="60" style="border-radius: 4px"/>
                      </template>
                    </el-image>
                  </el-col>
                  <el-col :span="19">
                    <div>
                      <el-tooltip effect="dark" :content="item.title" placement="top">
                        <el-text size="large" :truncated="true" style="color: var(--el-text-color-primary)">
                          {{ item.title }}
                        </el-text>
                      </el-tooltip>
                      <el-tooltip effect="dark" placement="top">
                        <template #content>
                          <div style="max-width: 400px">{{item.introduction}}</div>
                        </template>
                        <div class="question-temp">
                          <div class="multi-line-text line-clamp-2"
                               style="max-height: 36px;"
                          >{{ item.introduction }}
                          </div>
                        </div>
                      </el-tooltip>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="text-center" v-if="knowledgeName !== ''">
          <el-text type="info" class="font-size-s">
            <span>已选择知识库：《{{ knowledgeName }}》</span>
            <el-icon class="pointer" @click="clearKnowledge">
              <component is="Close"></component>
            </el-icon>
          </el-text>
        </div>
      </div>
    </div>
    <document-viewer :file-name="showFileName" :ext="showFileExt" v-model:show="showFileEnable" :url="showFileUrl"/>
    <!--		<el-dialog v-model="showDialog" :close-on-click-modal="false" append-to-body width="400" draggable title="请留下您宝贵的意见"
          center>

        </el-dialog>-->
  </div>
</div>
</template>
<script>
  import moment from 'moment'
  import {httpLikeHandle, getLikeQuestions} from '@/api/chat.js'
  import {ElMessage} from 'element-plus'
  import useAppStorage from '@/stores/application.js'
  import {getDocumentStr} from "@/utils/index.js"
  import {httpCreateNote} from "@/api/note.js"
  import useNoteStore from "@/stores/note.js"

  const appStore = useAppStorage()
  export default {
    props: {
      customClass: {
        type: String,
        default: ''
      },
      histories: {
        type: Array,
        default: []
      },
      inputAndEnter: {
        type: Function,
        default: () => {
        }
      },
      refreshQuestions: {
        type: Function,
        default: () => {
        }
      },
      showTools: {
        type: Boolean,
        default: true
      },
      isOutAct: Boolean,
      aiOutput: String,
      disable: Boolean,
      knowledgeName: {
        type: String,
        default: ''
      },
      clearKnowledge: Function,
      questions: Array,
      questionLoading: Boolean,
      showAppInput: Boolean,
      appInfo: {
        type: Object,
        default: () => {
          return {id: 0}
        }
      },
      selectApp: Function
    },
    data() {
      return {
        like_type: [0, 1, 2],
        cai_questions: [],
        showDialog: false,
        selectItem: null,
        prompt: '',
        question_id: [],
        showFileEnable: false,
        showFileUrl: '',
        showFileName: '',
        showFileExt: '',
        recommendApps: [],
        showApp: false,
        noteStore: null
      }
    },
    computed: {
      now() {
        return moment().format("YYYY-MM-DD HH:mm:ss")
      },
      historyLength() {
        return this.histories.length
      }
    },
    methods: {
      getFileExt(filename) {
        const name_arr = filename.split('.')
        if (name_arr.length <= 1) {
          return '._'
        } else {
          return '.' + name_arr[name_arr.length - 1]
        }
      },
      addDocument(text) {
        // const text = getDocumentStr(id)
        const pattern = /[\s\n.,!?;:，。！？；：’‘”“'"(){}（）【】[\]《》<>\\\/\-]/g
        httpCreateNote({
          folder_id: 0,
          title: text.replace(pattern, '').substring(0, 8),
          content: text,
          icon: 'Document',
          label_id_list: []
        }).then(() => {
          ElMessage.success('已加入笔记，请在笔记中查看和编辑')
          if (!this.noteStore) {
            this.noteStore = useNoteStore()
          }
          this.noteStore.getFolderListData()
        }).catch(() => {})
      },
      handleSelectApp(app) {
        const appCopy = {...app}
        appCopy.option_message = JSON.parse(appCopy.option_message)
        this.selectApp(appCopy)
      },
      downloadFile(item, preview = true) {
        const that = this
        const host = import.meta.env.VITE_BASE_API
        preview = preview ? 1 : 0
        const url = host +
            `/knowledge/download-docs?knowledge_id=${item.kid}&file_name=${item.name}&preview=${preview}`
        if (!preview) {
          window.open(url)
        } else {
          that.showFileExt = that.getFileExt(item.name)
          that.showFileName = item.name
          that.showFileUrl = url
          that.showFileEnable = true
        }
      },
      async submitSug() {
        if (this.prompt.trim() === "" && this.question_id.length === 0) {
          return
        }
        const response = await httpLikeHandle(this.selectItem.id, 2, this.prompt, this.question_id)
            .then(() => true).catch(() => false)
        if (response) {
          this.selectItem.like_type = 2
          ElMessage.success('我们已收到您宝贵的建议！')
          this.showDialog = false
        }
      },
      async likeHandle(item, type) {
        if (item.like_type !== 0 && item.like_type !== undefined) {
          return
        }
        let prompt = ''
        if (type === 2) {
          this.selectItem = item
          this.showDialog = true
          this.question_id = []
          this.prompt = ''
          return
        }
        const response = await httpLikeHandle(item.id, type, prompt).then(() => true).catch(() => false)
        if (response) {
          item.like_type = type
        }
      },
      getCaiQuestions() {
        getLikeQuestions().then(({list}) => {
          this.cai_questions = list
        }).catch(() => {
        })
      },
      messageScrollEnd() {
        this.$nextTick(() => {
          const box = document.getElementById('chat-section')
          const child = document.getElementById('chat-message-box')
          if (child.scrollHeight < box.clientHeight) {
            return
          }
          box.scrollTop = child.scrollHeight - box.clientHeight
        })
      },
      async setRecommendApps() {
        if (this.showTools) {
          this.recommendApps = await appStore.getApplications()
        }
      },
      moreApp() {
        appStore.setShow(true)
      }
    },
    mounted() {
      setTimeout(() => {
        this.showApp = true
      }, 800)
      this.messageScrollEnd()
      this.getCaiQuestions()
      this.setRecommendApps()
    },
    watch: {
      'historyLength'() {
        this.messageScrollEnd()
        setTimeout(() => {
          this.messageScrollEnd()
        }, 300)
      },
      'aiOutput'() {
        this.messageScrollEnd()
      },
      'questions'() {
        this.messageScrollEnd()
        setTimeout(() => {
          this.messageScrollEnd()
        }, 300)
      }
    }
  }
</script>
<style lang="scss">
  html.dark {
    .chat-message-box {
      .user {
        .message {
          background-color: rgba(149, 236, 105, 0.2);
          color: #BCBCBC;
        }

        .avatar {
          background: rgba(25, 195, 125, 0.5);
        }
      }

      .assistant {
        .message {
          background-color: rgba(244, 246, 248, 0.2);
          color: #BCBCBC;
        }

        .avatar {
          background: rgba(121, 137, 155, 0.3);
          color: rgba(255, 255, 255, 0.5);
        }
      }
    }
  }

  .sug-radio-button {
    margin: 0 10px 10px 0;

    //.el-radio-button__inner {
    //	border-left: var(--el-border);
    //	border-radius: 4px !important;
    //}
  }

  .chat-message-box {
    display: grid;
    overflow-y: auto;
    overflow-x: hidden;
    padding-top: 10px;
    width: 100%;

    .user,
    .assistant {
      width: calc(100vw - 440px);
    }

    .message-box {
      max-width: calc(100% - 75px);
    }

    .avatar-box {
      height: 80px;

      .avatar {
        width: 32px;
        height: 32px;
        padding: 3px;
        font-size: 24px;
        font-weight: 800;
        background: rgba(25, 195, 125, 0.8);
        color: var(--el-border-color-light);
        text-align: center;
        line-height: 24px;
        border-radius: 100%;
        border: 1px solid var(--el-border-color);
        overflow: hidden;

        .el-image {
          width: 32px;
          height: 32px;
          position: relative;
          top: -4px;
          left: -4px;
        }
      }
    }

    .time {
      font-size: 12px;
      line-height: 16px;
      color: #999999;
      position: relative;
      top: -5px;
    }

    .message {
      padding: 10px 20px;
      border-radius: 5px;
      margin-top: -4px;
      margin-bottom: 30px;
      position: relative;
      max-width: 100%;

      pre {
        white-space: break-spaces;
      }

      i {
        cursor: pointer;
        position: absolute;
        bottom: -22px;
        left: 0;

        &.primary {
          color: var(--el-menu-active-color)
        }

        &.info {
          color: var(--el-color-info);
          cursor: no-drop;
        }
      }
    }

    .user {
      .message {
        background: rgb(149, 236, 105);
        float: right;
        margin-right: 10px;

        i {
          right: 0;
          left: inherit;
        }
      }

      .avatar-box {
        float: right;
      }

      .time {
        margin-right: 10px;
        float: right;
      }
    }

    .assistant {
      .message {
        background: rgb(244, 246, 248);
        float: left;
        margin-left: 10px;
      }

      .avatar-box {
        float: left;

        .avatar {
          background: rgba(121, 137, 155, 0.3);
          color: rgba(255, 255, 255);
        }
      }

      .time {
        margin-left: 10px;
        float: left;
      }
    }
  }

  .chat-section {
    width: calc(100vw - 440px);
  }

  .recommend-apps {
    width: 900px;
    margin: 100px auto 0;

    .question-item {
      background: var(--el-bg-color);
      box-shadow: var(--el-box-shadow-light);
      padding: 8px;
      border-radius: 5px;
      margin-bottom: 14px;
      cursor: pointer;

      .question-temp {
        line-height: 18px;
        font-size: 13px;
        height: 36px;
        display: flex;
        align-items: center;
        color: var(--el-text-color-regular);
      }
    }
  }

  .sect {
    overflow-y: auto;
    overflow-x: hidden;
    height: calc(100vh - 140px);
    width: calc(100vw - 390px);
    position: absolute;
    top: 0;
    left: 0;
  }

  .data-file {
    background: transparent;
    margin-top: 15px;

    .bg {
      border: none !important;

      .el-collapse-item__header {
        background: transparent !important;
        border: none;
        width: auto;
      }

      .el-collapse-item__wrap {
        background: transparent !important;
        border: none;
      }

      .el-link__inner {
        font-size: 13px;
        margin-top: -2px;
      }

      .el-icon {
        position: inherit;
      }
    }
  }
</style>